package com.hangzhou.xyj.engine.impl;


import com.hangzhou.xyj.engine.LocationEngine;
import com.hangzhou.xyj.engine.TimeOutHandler;
import com.hangzhou.xyj.event.LocationRespEvent;
import com.hangzhou.xyj.event.ReqLocationEvent;
import com.hangzhou.xyj.event.TimeOutEvent;
import com.hangzhou.xyj.event.base.EventCode;
import com.hangzhou.xyj.model.XXLocation;
import com.hangzhou.xyj.utils.EventBusUtil;

import android.util.Log;

import org.greenrobot.eventbus.Subscribe;


/**
 * Created by dfb on 2015/8/25.
 * 定位管理器
 */
public class LocationEngineImpl implements EventCode, LocationEngine {

    private static final String TAG = LocationEngineImpl.class.getSimpleName();

    private static final int REQ_LOCATION = 1;
    private static final int REQ_LOCATION_CONFIG = 2;

    private long TIME_OUT = 5000;

    private int REQ_TYPE = REQ_LOCATION;

    private TimeOutHandler mTimeOutHandler;

    private XXLocation mLocation;

    private Object mEventTag;
    //标识定位和获取配置任务是否完成
    private boolean isReqLocationFinish = false;
    private boolean isGetConfigFinish = false;

    public LocationEngineImpl() {
        mTimeOutHandler = new TimeOutHandler();
    }

    @Override
    public void setEventTag(Object mEventTag) {
        this.mEventTag = mEventTag;
    }

    @Override
    public void setTimeOut(long timeOut) {
        this.TIME_OUT = timeOut;
    }

    /**
     * 请求定位
     * 接收事件为 LocationRespEvent
     */
    @Override
    public void requestLocation() {
        //注册自己，用完销毁
        EventBusUtil.register(this);
        this.REQ_TYPE = REQ_LOCATION;
        startReqLocation();
    }


    /**
     * 开启请求定位和超时机制
     */
    private void startReqLocation() {
        Log.d(TAG, "==startReqLocation()==");

        /********启动前:置2个任务都未完成******/
        isReqLocationFinish = false;
        isGetConfigFinish = false;

        /********启动超时处理器******/
        mTimeOutHandler.setEventTag(TAG);
        mTimeOutHandler.setTimeOut(TIME_OUT);
        mTimeOutHandler.start();

        /********发送请求定位事件********/
        ReqLocationEvent event = new ReqLocationEvent();
        if (mEventTag != null) {
            event.setTag(TAG);  //请求定位反馈给自己，而不是mEventTag外部请求调用者
        }
        EventBusUtil.postEvent(event);
    }

    /**
     * 系统定位成功
     */
    @Subscribe
    public void onEventMainThread(LocationRespEvent event) {
        if (!TAG.equals(event.getTag())) {
            return;
        }

        if (mTimeOutHandler.isTimeOut()) {
            Log.d(TAG, "==LocationRespEvent==time out");
            return;
        }

        switch (event.getCode()) {
            case START:
                Log.d(TAG, "LocationRespEvent====start");
                return;
            case SUCCESS:
                Log.d(TAG, "LocationRespEvent====success");
                break;
            case FAIL:
                Log.d(TAG, "LocationRespEvent====fail");
                break;
            default:
                return;
        }

        //标记定位任务完成
        isReqLocationFinish = true;

        XXLocation location = event.getData();
        if (location == null) {
            return;
        }

        this.mLocation = location;
    }


    /**
     * 超时事件
     */
    @Subscribe
    public void onEventMainThread(TimeOutEvent event) {
        //只接收本类tag
        if (!TAG.equals(event.getTag())) {
            return;
        }

        switch (event.getCode()) {
            case START:
                Log.d(TAG, "timeout handler start....");
                return;
            case SUCCESS:
                Log.d(TAG, "timeout handler already timeout....");
                String timeOutMsg = "";
                if (!isReqLocationFinish) {
                    timeOutMsg = "request location timeout";
                } else if (!isGetConfigFinish) {
                    timeOutMsg = "get system config timeout";
                }
                reqLocationFail(timeOutMsg, 0);
                break;
        }
    }

    /**
     * 调用该方法为：超时或定位失败或获取配置失败，所以必须取消所有操作
     */
    private void reqLocationFail(String errMsg, int errCode) {
        Log.e(TAG, "==request location and system config fail: " + errMsg + " errCode:" + errCode);
        //标记系统地址为null:防止应用退出后再次进来，获取配置失败，使用了原来的地址
//        DydApplication.sAppLogicLocation = null;
        //停止超时处理器
        mTimeOutHandler.cancel();
        //停止转换地区编码
//        DydApplication.getRequestQueue().cancelAll(API.Server.GETAREACODE);
        //停止获取系统配置
//        DydApplication.getRequestQueue().cancelAll(API.Server.SYSTEM_SETTING);
        //发送取消定位消息
//        EventBusUtil.postEvent(new CancelReqLocationEvent());
        //发送失败信息
//        EventBusUtil.postEvent(new LocationAndConfigEvent(FAIL,new ExceptionEvent(errCode,errMsg)).setTag(mEventTag));
        //用完销毁
        EventBusUtil.unregister(this);
    }
}
